namespace EyeOpen.Web.Hosting
{
	using System;
	using System.Collections.Generic;
	using System.IO;
	using System.Reflection;
	using System.Web.Hosting;

	public class EmbeddedVirtualFile 
		: VirtualFile
	{
		private readonly IDictionary<string, Tuple<string, string>> virtualPathDictionary;

		public EmbeddedVirtualFile(string virtualPath, IDictionary<string, Tuple<string, string>> virtualPathDictionary)
			: base(virtualPath)
		{
			this.virtualPathDictionary = virtualPathDictionary;
		}

		public override Stream Open()
		{
			var assemblyAndPath = virtualPathDictionary[VirtualPath];
			
			var assembly = 
				Assembly.Load(assemblyAndPath.Item1);
			
			var stream = assembly
				.GetManifestResourceStream(assemblyAndPath.Item2);

			if (stream == null)
			{
				throw new NullReferenceException(string.Format("Cannot find a resource with key \"{0}\".", assemblyAndPath.Item2));	
			}

			return 
				stream;
		}
	}
}